<template>
  <div class="h-full w-full" style="height:100%;overflow: auto;">
    <SplitPanel :style="{ 'flex-direction': 'row !important' }" class="user-page-box">
      <template #left-content>
        <div class="flex justify-between flex-col h-full">
          <Tree :defaultExpandAll=true :treeData="treeData" :onSelect="setGroupSelected">
            <template #title="treeItem">
              <span>
                {{ treeItem.title }}
              </span>
              <NDropDown :show-default=true :dropItems="dropItems" @click="(val) => handleTreeItemClick(val, treeItem)"
                class="ml-10px" />
            </template>
          </Tree>
          <a-modal v-model:open="confirmVisible" title="确认删除" @ok="handleDeleteConfirm"
            @cancel="confirmVisible = false">
            确认要删除该项吗？
          </a-modal>
        </div>
      </template>
      <template #right-content>
        <div>正在设置的方向条件: {{props.connectionName}}</div>
        <div style="background-color:#f4f2f2;margin-top: 10px;padding-top: 5px;padding-bottom: 5px;">
          <label style="padding-left: 5px;padding-right: 10PX;">规则组</label>
          <a-button tertiary style="text-align: right;" type="info" @click="addDataRow(createOperRunData)">
            添加规则
          </a-button>          
        </div>
        <a-table :columns="createRunColumns" :data-source="createOperRunData">
          <template #bodyCell="{ column, record, text, index }">
            <template v-if="column.key === 'businessSelected'">
              <div style="display: flex; gap: 8px;">
                <a-cascader :options="workflowOptions" v-model:value="record.businessSelected" expand-trigger="hover"
                  style="width: 100%;min-width: 200px;" placeholder="请选择" :show-search="{ filter }"
                  @change="($event, selectedOptions) => handleBusinessSlected($event, selectedOptions, record)" />
              </div>
            </template>
            <template v-if="column.key === 'NODE_ACTION_NICK_NAME'">
              <div style="display: flex; gap: 8px;">
                <a-select v-model:value="record.NODE_ACTION_NICK_NAME" style="width: 100%;min-width: 100px;"
                  :options="convertOptions" @change="handleBusinessConvert(record, $event)" />

              </div>
            </template>
            <template v-else-if="column.key === 'businessRealtion'">
              <div style="display: flex; gap: 8px;">
                <a-select v-model:value="record.businessRealtion" style="width: 100%;min-width: 100px;"
                  :options="setBuinessSelectOptions(record.operType)"
                  @change="handleBusinessRelation(record, $event)" />
              </div>
            </template>
            <template v-else-if="column.key === 'businessValue'">
              <div style="display: flex; gap: 8px;">
                <a-input v-model:value="record.businessValue" @change="(e) => handleBuisnessValue(record)" />
              </div>
            </template>
          </template>
        </a-table>
      </template>
    </SplitPanel>
  </div>
</template>



<script lang="tsx" setup>
import { reactive, ref, h, watch, unref, onMounted } from 'vue';
import type { TableColumn } from '@/components/core/dynamic-table';
import { Tree, TreeProps, Input, Button, Popconfirm, Modal, Alert, SelectProps, Cascader, Select } from 'ant-design-vue';
import type { CascaderProps } from 'ant-design-vue';
import type { ShowSearchType } from 'ant-design-vue/es/cascader';
import { message } from 'ant-design-vue';
import { conditionRowData, createConditionRowData } from '@/components/design/components/DesignerCommCore/columns';
import { Percent } from 'lucide-vue-next';
import { select } from 'tiny-svg';
import type { TreeDataItem } from '@/core/permission/utils';
import { SplitPanel } from '@/components/basic/split-panel';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import NDropDown from '@/components/business/ruleCondition/index.vue';
import { tr } from 'element-plus/es/locale/index.mjs';
import { connectionAttr } from '@/store/modules/connectionAttr';
import {processInfo} from '@/store/modules/processInfo';
import { ConnectionConditionAttr } from '@/components/design/components/DesignerCommCore/ConnectionAttr';
import {getflowVariables } from '@/api/flow/review';
import {getFormDataJson} from '@/utils/common';
import { it } from 'node:test';



const props = defineProps({
  sequeid: {
    type: String as PropType<string>,
    default: undefined,
  },
  connectionName: {
    type: String as PropType<string>,
    default: undefined,
  },  
});

const connecitonAttrStore = connectionAttr();
const proceStore=processInfo();
const dropItems = ref([]);

const selectedGroupId = ref("0-0");
const confirmVisible = ref(false);
//
const setGroupSelected = (selectkeys) => {
  selectedGroupId.value = selectkeys[0];
  if(selectedGroupId.value==""||selectedGroupId.value == undefined)
  {
    message.warning("请选择条件组。")
    return;
  }
  //显示右侧数据
  traverse(treeData.value, handleNode,"", selectedGroupId.value);
}


const createOperRunData = ref(createConditionRowData());
//const createOperRunData = ref([]);

const treeData = ref<TreeProps['treeData']>([
  {
    title: '条件组',
    key: '0-0',
    parentId: '0',
    operationRelation: 'or',
    /*
    children: [
     
      {
        title: '并且',
        key: '0-0-0',
        parentId: '0-0',
        operationRelation: 'and',
        conditions: [
          { id: '43', parentId: '0-0-0', operType: '', businessSelected: 'varible.name', businessRealtion: '==', businessValue: 'admin' },
          { id: '34', parentId: '0-0-0', operType: '', businessSelected: 'varible.age', businessRealtion: '>', businessValue: '30',logicOperation：'and' },
        ],
        children: [
          { title: '或者', parentId: '0-0-0', key: '0-0-0-0', operationRelation: 'or' },
          { title: '并且', parentId: '0-0-0', key: '0-0-0-1', operationRelation: 'and' },
        ],
      },
      {
        title: '或者',
        key: '0-0-1',
        parentId: '0-0',
        operationRelation: 'or',
        children: [{ key: '0-0-1-0', parentId: '0-0-1', title: '并且', operationRelation: 'and' }],
      },
      
    ],
    */
  },
]);

function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(
    /[xy]/g,
    function (c) {
      var r = (Math.random() * 16) | 0,
        v = c == 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    }
  );
}
function removeTreeListItem(treeList, key) { // 根据id属性从数组（树结构）中移除元素
  if (!treeList || !treeList.length) {
    return
  }
  for (let i = 0; i < treeList.length; i++) {
    if (treeList[i].key === key) {
      treeList.splice(i, 1);
      break;
    }
    removeTreeListItem(treeList[i].children, key)
  }
}

//删除   1）删除conditions 2）删除 后辈的及conditions  
function handleDeleteConfirm() {    
  if(selectedGroupId.value===undefined)
  {
    message.warning("请先选择要删除的条件组");
    confirmVisible.value = false;
    return;
  }     
  removeTreeListItem(treeData.value,selectedGroupId.value);

  confirmVisible.value = false;
}
// 定义处理每个节点的函数
function handleNode(node, operationKey, selectKey) {
  if (node.key === selectKey) {
    if (operationKey === 'del') {
      if (node.title === '条件组') {
        message.warning('根节点不能删除！');
        return true;
      }
      confirmVisible.value = true;
      return true;
    }
    if (operationKey === 'addChildAnd') {
      node.children = node.children || [];
      node.children.push({ title: '并且', parentId: node.key, key: uuidv4(), operationRelation: 'and' });
      return true;
    }
    if (operationKey === 'addChildOr') {
      node.children = node.children || [];
      node.children.push({ title: '或者', parentId: node.key, key: uuidv4(), operationRelation: 'or' });
      return true;
    }    
    createOperRunData.value = node.conditions || [];
    return true;
  }
  else
    return false;

}

function traverse(jsonArray, callback, operationKey, selectKey) {
  jsonArray.forEach((item, index, array) => {
    if (callback(item, operationKey, selectKey))
      return;
    if (item.children) {
      traverse(item.children, callback, operationKey, selectKey);
    }
  });

}
//  operationSelected: 新增下级，删除；treeNodeSelected：选定树节点
const handleTreeItemClick = (operationSelected, treeNodeSelected) => {
  traverse(treeData.value, handleNode, operationSelected.key, treeNodeSelected.key);
};


//新增行 
const addDataRow = (operData) => {
  
  if (selectedGroupId.value == '0-0') {
    message.warning("请选择左侧条件组，注意不能选根节点。")
    return;
  }
  if(selectedGroupId.value==""||selectedGroupId.value == undefined)
  {
    message.warning("请选择左侧条件组，注意不能选根节点。")
    return;
  }

  const newRow = {
    key: uuidv4(),
    parentId: selectedGroupId.value,
    operType: "string",
    businessSelected: "",
    businessRealtion: "",
    businessValue: "",
    logicOperation:""
  };
 // operData.push(newRow);
  traverseFindParent(treeData.value, newRow, addNewCondition);
}

function traverseFindParent(jsonArray, newRow, addNewCondition) {
  jsonArray.forEach((item, index, array) => {
    if (item.key === newRow.parentId) {
      addNewCondition(newRow, item);
      return;
    }
    if (item.children) {
      traverseFindParent(item.children, newRow, addNewCondition);
    }

  });

}

function addNewCondition(newRow, item) {
  item.conditions = item.conditions || [];
  newRow.logicOperation = item.operationRelation;
  item.conditions.push({ key: newRow.key, parentId: newRow.parentId, businessSelected: '', businessRealtion: '', businessValue: '',logicOperation:newRow.logicOperation});
  createOperRunData.value = item.conditions;
}


const createRunColumns: TableColumn<conditionRowData> = [
  {
    title: '操作名称',
    key: 'businessSelected',
  },
  {
    title: '操作设置(慎用)',
    key: 'NODE_ACTION_NICK_NAME',
  },
  {
    title: '操作关系',
    key: 'businessRealtion',
  },
  {
    title: '操作值',
    key: 'businessValue',

  },
  {
    title: '操作',
    key: 'actions',
    align: 'center',
    width: '20%',
    customRender: ({ text, record, index }) => {
      return <Popconfirm title='确认删除吗？' onConfirm={(e) => removeRow(createOperRunData, record.key)}><a>删除</a></Popconfirm>
    }
  },
];

const setBuinessSelectOptions = (selectOptions) => {
  if (selectOptions === 'person') {
    return persionOptions;
  }
  else if(selectOptions==="string") {
    return stringOptions;
  }
  else if(selectOptions === "int"){
    return numberOptions;
  }
};

function traverseFindCondition(jsonArray, record, updateCondition) {
  jsonArray.forEach((item, index, array) => {
    if (item.key === record.key) {
      updateCondition(record, item);
      return;
    }
    if (item.children) {
      traverseFindCondition(item.children, record, updateCondition);
    }
    if (item.conditions) {
      traverseFindCondition(item.conditions, record, updateCondition);
    }    
  });

}

function updateCondition(record, item) {
  item.businessSelected = record.businessSelected;
  item.businessRealtion = record.businessRealtion;
  item.businessValue = record.businessValue;
}

function handleCodintionChanged(record) {
  traverseFindCondition(treeData.value, record, updateCondition);
}

//选择变量元素，同步更新整个条件组treedata对应内容
//record 就是当个操作条件内容   
const handleBusinessSlected = (value, select, record) => {
  debugger;
  if(value.length<=1)
    return;
  console.log(value[value.length-1]); 
  /*
  select.forEach((item, index, array) => {
    //选择不是最后一层，现在设置不能选择，记不清了，待确认
    
    if (item.children) {
    }
    else {
      record.operType = item.dataType;      
      record.businessSelected = value;
      //处理不同的数据类型，不同的操作符//setBuinessSelectOptions(record.operType);
    }
  });*/
  let dataType =  getDataType(value);
  record.operType = dataType;      
  record.businessSelected = value;
  setBuinessSelectOptions(record.operType);
  handleCodintionChanged(record);
}

function getDataType(vaules){
  //
  //label: '流程数据项',
   // value: 'workflowInstance',
   // children: [
   let firstLevel;
   let datatype;
  workflowOptions.value?.forEach((item, index, array) => {
     if(item.value===vaules[0])
      {
        firstLevel = item;               
      }
  });
  firstLevel.children.forEach((item, index, array) => {
     if(item.value===vaules[vaules.length-1])
      {
        datatype = item.dataType;
      }
  });
 return datatype;





} 



const handleBusinessRelation = (record, value) => {
  record.businessRealtion = value;
  handleCodintionChanged(record);
};

const handleBuisnessValue = (record) => {
  handleCodintionChanged(record);
}


const handleBusinessConvert = (record, value) => {
  record.operType = value;

};

const convertOptions: SelectProps['options'] = ([
  {
    value: 'person',
    label: '设为人员',
  },
  {
    value: '!=',
    label: '设为岗位',
  },
  {
    value: 'contains',
    label: '设为部门',
  },
  {
    value: 'not contains',
    label: '设为群组',
  },
]);

const persionOptions: SelectProps['options'] = ([
  {
    value: '=',
    label: '人员属于',
  },
  {
    value: '!=',
    label: '人员不属于',
  },

]);

const operOptions = ref<SelectProps['options']>([

]);

const stringOptions: SelectProps['options'] = ([
  {
    value: '=',
    label: '等于',
  },
  {
    value: '!=',    
    label: '不等于',
  },
  {
    value: 'contains',
    label: '包含',
  },
  {
    value: 'not contains',
    label: '不包含',
  },
  {
    value: 'isEmpty',
    label: '为空',
  },
  {
    value: 'not isEmpty',
    label: '不为空',
  },
]);

const numberOptions: SelectProps['options'] = ([
 {
    value: '>',
    label: '大于',
  },
  {
    value: '<',
    label: '小于',
  },
  {
    value: '=',
    label: '等于',
  },
  {
    value: '!=',    
    label: '不等于',
  },  
]);

const workflowOptions =   ref<CascaderProps['options']>([

]);//  ref([]);
//const workflowOptions: CascaderProps['options']  // = [
  /*
  {
    label: '流程数据项',
    value: 'workflowInstance',
    children: [
      {
        label: '起草人ID',
        value: 'admin',
        dataType: 'string',
      },
      {
        label: '起草人名称',
        value: '112',
        dataType: 'string',
      },
    ],
  },
  {
    label: '业务表单项',
    value: 'apply',
    children: [
    {
        label: '起草人ID',
        value: 'admin',
        dataType: 'string',
      },
      {
        label: '起草人名称',
        value: 'name',
        dataType: 'string',
      },
      {
        label: '请假天数',
        value: 'days',
        dataType: 'number',
      },
      {
        label: '是否年休',
        value: '年休',
        dataType: 'bool',
      },
      {
        label: '发起时间',
        value: '2024.11.23',
        dataType: 'date',
      },
    ],
  },
  {
    label: '流程临时变量',
    value: 'varible',
    children: [
      {
        label: '部门',
        value: 'depart',
        dataType: 'string',
      },
    ],
  },
  */
//];
const filter: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
};



//删除行
const removeRow = (operData, key) => {
   operData.value = operData.value.filter((item) => item.key !== key);
   removeTreeListItem(treeData.value,key); 

};

const clearTrashData =(treeData)=>{
  treeData.forEach((item, index, array) => {    
    if (!item.children&&!item.conditions) {
      removeTreeListItem(treeData,item.key);
    }
    if(item.children)
    {
      clearTrashData(item.children);
    }
    
  });

}
const formKeyList=ref<any>([]); 
const loadVariables = async (formId)=>
{  
  const res = await getflowVariables(formId);    
    if (res && res.status == '200') {     
    workflowOptions.value?.push(JSON.parse(res.result.workflowInstance));
    workflowOptions.value?.push(JSON.parse(res.result.varibleInstance));    
    const mapJSON = JSON.parse(res.result.formJson);
    formKeyList.value=getFormDataJson(mapJSON.list);   
    let businessInstance = JSON.parse(res.result.businessInstance);
    businessInstance.children = businessInstance.children.concat(formKeyList.value);    
    workflowOptions.value?.push(businessInstance)      
    return true;
      
    } else {
      message.error('获取参数列表失败。');     
      return res;
    }
    
}

const onSubMit = async () => {  
  var processDefinitionId =proceStore.procInfo.id;
  var { connectioVaule } = connecitonAttrStore.getConnectionByNo(props.sequeid);
  //console.log(treeData.value);
  //todo 待处理 去掉没有条件的分组，去掉后，childern是 [],length=0
  //clearTrashData(treeData.value);
  //console.log(treeData.value);
  

  if (treeData.value[0].children) {
    if (processDefinitionId === "" || processDefinitionId === undefined 
            || processDefinitionId === null||connectioVaule===null) {
      let newConnection: ConnectionConditionAttr;
      newConnection = {
        connectionNo: props.sequeid,
        connectionName: props.connectionName,
        processDefinitionId: "",
        expressType: "feel",
        expressBody: treeData.value,
      };
      connecitonAttrStore.addConnection(newConnection);
    }
    else {      
      
      
      connectioVaule = {
        connectionNo: props.sequeid,
        connectionName: props.connectionName,
        processDefinitionId: connectioVaule.processDefinitionId,
        expressType: "feel",
        expressBody: treeData.value,
      };
      connecitonAttrStore.updateConnectionByNo(props.sequeid, connectioVaule);
    }
    console.log(treeData.value)
    return "hasvalue";
  }
  return "novalue";
};
//上级父页面调用
defineExpose({
  handleSubmit: onSubMit,
});

onMounted(() => {
  //treeData
  var { hasVaule, connectioVaule } = connecitonAttrStore.getConnectionByNo(props.sequeid);
  if (hasVaule)
    treeData.value = connectioVaule.expressBody;

  var formId =proceStore.procInfo.formId;
  if(formId===''||formId ==null){
    message.error('请设置流程的主表单。');     
  }
  else 
     loadVariables(formId);


});

</script>

<style lang="less" scoped>
@import '@/styles/navTheme.less';
@classBacks: user-page-box;
.customSetStyle(@classBacks, background-color, 'content-back-user');

:deep(.ant-tree) {
  flex: 1;
}

.testtitle {
  width: 100%;
  overflow: hidden;
  line-height: 30px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.testitem {
  position: relative;
  display: flex;
  justify-content: space-between;
  width: 150px;
  align-items: center;
}

.custom-width {
  width: 300px;
  /* 指定宽度 */
}
</style>